layui.config({
    base: 'assets/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index', //主入口模块
    formSelects: '../layui/lay/modules/formSelects-v4'
}).use(['index', 'tree', 'form', 'formSelects'], function(){
    var $ = layui.$, tree = layui.tree, form = layui.form, formSelects = layui.formSelects;

    var id = $('#id').val();
    var data = {'id': id};
    post('adminUser/toEdit', data, false,function (data) {
        var ops = "", roleIds = [];
        data.roles.forEach(function (val) {
            ops += '<option value="'+val.id+'">'+val.name+'</option>';
            roleIds.push(val.id);
        });
        $('#roles').append(ops);
        formSelects.render("roles");

        var adminUser = data.adminUser;
        if(adminUser){
            $('#username').val(adminUser.username);
            if(id != ''){
                $('#username').attr('readonly', tree)
            }
            if(id != ''){
                $($('#password').parent().parent()).hide();
            }
            $('#nickname').val(adminUser.nickname);
            $("#realname").val(adminUser.realname);
            $('#password').val(adminUser.password);

            //回选角色
            var selectRoleIds = [];
            data.userRoles.forEach(function (val) {
                if(roleIds.indexOf(val.id) > -1){
                    selectRoleIds.push(val.id);
                }
            });
            formSelects.value("roles", selectRoleIds);
        }
    });

    //校验
    form.verify({
        'role-verify': function (value, item) {
            var checkData = formSelects.value('roles', 'val');
            if(checkData.length <= 0){
                return '请至少选择一个角色';
            }
            var roleIds = JSON.stringify(checkData);
            $("#roleIds").val(roleIds);

            var roleNames = formSelects.value('roles', 'nameStr');
            $('#roleNames').val(roleNames);
        }
    });
});